﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Lavka.Models;

namespace Lavka.Core
{
    public static class CartHelper
    {
        public static List<Products> Cart
        {
            get
            {
                if (HttpContext.Current.Session["UserCart"] == null) HttpContext.Current.Session["UserCart"] = new List<Products>();
                return (List<Products>)HttpContext.Current.Session["UserCart"];
            }
            set
            {
                HttpContext.Current.Session["UserCart"] = value;
            }
        }
        public static void AddProductById(int productId, LavkaDbEntities context)
        {
            var product = context.Products.Where(p => p.ProductId == productId).FirstOrDefault();
            if (product != null)
            {
                if (Cart.Where(c => c.ProductId == productId).Count() == 0) Cart.Add(product);
            }
        }
        public static decimal GetSumPrice(LavkaDbEntities context)
        {
            decimal SumPrice = (decimal) Cart.Aggregate<Products, decimal?>(0, (current, t) => current + Convert.ToDecimal(ProductsHelper.GetProductPrice(t, context)));
            return SumPrice;
        }
        public static decimal? RecalucatePrice(string[] itemNums, LavkaDbEntities context)
        {
            decimal? SumPrice = 0;
            for (int i = 0; i < Cart.Count; i++)
            {
                SumPrice += Convert.ToDecimal(ProductsHelper.GetProductPrice(Cart[i], context))*Convert.ToInt32(itemNums[i]);
            }
            return SumPrice;
        }
        public static bool IsProductInCart(Products product)
        {
            if (Cart.Where(c => c.ProductId == product.ProductId).Count() > 0) return true;
            return false;
        }
        public static void DeleteItem(int productId)
        {
            var product = Cart.Where(c => c.ProductId == productId).FirstOrDefault();
            Cart.Remove(product);
        }
        public static void ClearCart(LavkaDbEntities context)
        {
            Cart.Clear();
        }
    }
}